package com.zp.self.module.工具.json转换.json_csv;

import org.apache.commons.io.FileUtils;
import org.json.*;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/8/10 17:39
 * @description ：大json转换为csv
 */
public class Json2CsvMaxFile {

    public static String inPath = "C:\\Users\\peng.zeng\\Desktop\\data2.json";
    public static String outPath = "C:\\Users\\peng.zeng\\Desktop\\210111466.csv";

    public static void main(String[] args) throws Exception {
        maxJson2Csv(inPath, outPath);
    }

    private static void maxJson2Csv(String inFile, String outFile) throws Exception {
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inFile));
        // 用5M的缓冲读取文本文件
        int cache = 5 * 1024 * 1024;
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), cache);

        //循环读取字符
        System.out.println("开始读取");
        String init = "";
        char[] ch = new char[cache];
        JSONArray jsonArraya = null;
        JSONArray names = null;
        boolean haveHead = false;
        while ((reader.read(ch)) != -1) {
            String s = new String(ch);
            if (s.contains("[") || s.contains("]")) {
                s = s.replace("[", "");
                s = s.replace("]", "");
            }
            int end = s.lastIndexOf("}");
            String substring = s.substring(0, end + 1);
            jsonArraya = new JSONArray("[" + init + substring + "]");
            if (s.length() >= (end + 2)) {
                init = s.substring(end + 2);
            } else {
                init = "";
            }
            ch = new char[cache];

            //获取表头
            if (!haveHead && jsonArraya != null) {
                haveHead = true;
                JSONObject jo = jsonArraya.optJSONObject(0);
                names = jo.names();
                if (names != null) {
                    String csv = CDL.rowToString(names);
                    FileUtils.writeStringToFile(new File(outFile), csv, Charset.defaultCharset(), true);
                } else {
                    System.out.println("获取表头失败了--");
                    throw new Exception();
                }
            }
            //  循环
            String csv = CDL.toString(names, jsonArraya);
            FileUtils.writeStringToFile(new File(outFile), csv, Charset.defaultCharset(), true);
        }
        System.out.println("执行结束");
        reader.close();
    }

    public static String Json2Csv(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        String csv = CDL.toString(jsonArray);
        return csv;
    }
}
